package com.cjk.foundation.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import com.cjk.foundation.entity.GroupEntity;
import com.cjk.foundation.orm.IdReceiver;

@Repository
public interface GroupDao {

	public List<GroupEntity> selectAll(@Param("userId") Integer userId, @Param("isIncludeRoot") boolean isIncludeRoot);

	@ResultMap("resultMap")
	@Select("select * from `group` where lft > #{lft} and rgt < #{rgt} and lvl = #{lvl}")
	public List<GroupEntity> selectListByCondition(@Param("rgt") Integer rgt, @Param("lft") Integer lft, @Param("lvl") Integer lvl);

	@Select("select id from `group` where lft >= #{lft} and rgt <= #{rgt}")
	public List<Integer> selectIdsByParentId(@Param("rgt") Integer rgt, @Param("lft") Integer lft, @Param("userId") Integer userId);

	@Update("update `group` set name = #{name} where id = #{id}")
	public void update(@Param("id") Integer id, @Param("name") String name);

	@ResultMap("resultMap")
	@Select("select * from `group` where lvl = 1 and user_id = #{userId}")
	public GroupEntity selectRootGroup(@Param("userId") Integer userId);

	@ResultMap("resultMap")
	@Select("select * from `group` where id = #{id}")
	public GroupEntity selectById(@Param("id") Integer id);

	// 新增分组 start
	@Select("select rgt from `group` where id = #{id} and user_id = #{userId}")
	public Integer selectRgtByGroupId(@Param("id") Integer id, @Param("userId") Integer userId);

	@Update("update `group` set rgt = rgt + 2 where rgt >= #{rgt} and user_id = #{userId}")
	public void updateRgt(@Param("rgt") Integer rgt, @Param("userId") Integer userId);

	@Update("update `group` set lft = lft + 2 where lft >= #{rgt} and user_id = #{userId}")
	public void updateLft(@Param("rgt") Integer rgt, @Param("userId") Integer userId);

	public void insertBySelect(@Param("receiver") IdReceiver<?> receiver, @Param("name") String name,
			@Param("description") String description, @Param("parentId") Integer parentId);
	// 新增分组 end

	// 删除分组 start
	@Delete("delete from `group` where lft >= #{lft} and rgt <= #{rgt} and user_id = #{userId}")
	public void delete(@Param("rgt") Integer rgt, @Param("lft") Integer lft, @Param("userId") Integer userId);

	@Update("update `group` set lft = lft - (#{rgt} - #{lft} + 1) where lft > #{lft} and user_id = #{userId}")
	public void updateDeleteLft(@Param("rgt") Integer rgt, @Param("lft") Integer lft, @Param("userId") Integer userId);

	@Update("update `group` set rgt = rgt - (#{rgt} - #{lft} + 1) where rgt > #{rgt} and user_id = #{userId}")
	public void updateDeleteRft(@Param("rgt") Integer rgt, @Param("lft") Integer lft, @Param("userId") Integer userId);
	// 删除分组 end
}
